<template>
    <el-form
        ref="ruleFormRef"
        style="max-width: 100%"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
    >
        <el-form-item label="账号" prop="account">
            <el-input v-model="ruleForm.account" placeholder="请输入账号" :disabled="ruleForm.id !== 0"/>
        </el-form-item>
        <el-form-item label="币种" prop="currency">
            <el-input v-model="ruleForm.currency" placeholder="请输入币种"/>
        </el-form-item>
        <el-form-item label="行号" prop="bankCode">
            <el-input v-model="ruleForm.bankCode" placeholder="请输入行号"/>
        </el-form-item>
        <el-form-item label="银行地址" prop="bankAddress">
            <el-input v-model="ruleForm.bankAddress" placeholder="请输入银行地址"/>
        </el-form-item>
        <el-form-item label="账户管理员" prop="accountManager">
            <el-input v-model="ruleForm.accountManager" placeholder="请输入账户管理员"/>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
            <el-input v-model="ruleForm.remarks" placeholder="备注"/>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm()">提交</el-button>
            <el-button @click="emitCancel">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import axios from "axios";
import {reactive, ref, watch} from 'vue';
import type {ComponentSize, FormInstance, FormRules} from 'element-plus';
import {ElMessage} from 'element-plus';
import type {Account} from "@/types/basic/account.ts";
import request from '@/util/request'

// 定义 validator 类型，符合 Element Plus 的要求
type Validator = (
    rule: any,
    value: string,
    callback: (error?: Error) => void
) => void;

const emit = defineEmits(['submit-success', 'cancel']);

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<Account>({
    id: 0,
    account: '',
    currency: '',
    bankCode: '',
    bankAddress: '',
    accountManager: '',
    remarks: '',
    createUid: 0,
    createDate: '',
    updateUid: 0,
    updateDate: '',
    isDelete: 0
});

const originalCode = ref<string>('');

// 校验客户编码唯一性
const checkCode: Validator = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请输入账号'));
        return;
    }

    // 编辑模式下，如果账户未修改，直接通过校验
    if (ruleForm.id !== 0 && value === originalCode.value) {
        callback();
        return;
    }

    request.post(`basic/Account/selectAccountByCode?code=${value}`)
        .then(response => {
            if (response.data.code !== "200") {
                callback(new Error(response.data.msg || '接口返回错误'));
                return;
            }

            if (response.data.data) {
                callback(new Error('账号已存在'));
            } else {
                callback();
            }
        })
        .catch(error => {
            console.error('校验账号失败:', error);
            callback(new Error('校验账号失败，请稍后重试'));
        });
};

const rules = reactive<FormRules<Account>>({
    account: [
        {required: true, message: '请输入账号', trigger: ['blur', 'change']},
        {min: 3, max: 10, message: '账号长度应为3到10个字符', trigger: ['blur', 'change']},
        {validator: checkCode, trigger: "blur"}
    ],
    currency: [
        {required: true, message: '请输入币种', trigger: ['blur', 'change']},
        {min: 2, max: 10, message: '币种长度应为2到10个字符', trigger: ['blur', 'change']}
    ],
    bankCode: [
        {required: true, message: '请输入行号', trigger: ['blur', 'change']},
        {min: 2, max: 10, message: '行号长度应为2到10个字符', trigger: ['blur', 'change']}
    ],
    bankAddress: [
        {required: true, message: '请输入银行地址', trigger: ['blur', 'change']},
        {max: 100, message: '银行地址长度不能超过100个字符', trigger: ['blur', 'change']}
    ],
    accountManager: [
        {max: 10, message: '账户管理员长度不能超过10个字符', trigger: ['blur', 'change']}
    ],
    remarks: [
        {required: true, message: '请输入备注', trigger: ['blur', 'change']},
        {max: 10, message: '备注长度不能超过100个字符', trigger: ['blur', 'change']}
    ]
});

const props = defineProps<{
    account?: Account | null; // 可选的客户数据，用于编辑
}>();

// 监听 account 属性，预填表单
watch(() => props.account, (newAccount) => {
    if (newAccount) {
        Object.assign(ruleForm, {
            ...newAccount,
            createdBy: Number(localStorage.getItem("userId") || "0"),
            updateId: localStorage.getItem("userId") || ""
        });
        originalCode.value = newAccount.account; // 设置原始编码
    } else {
        originalCode.value = ''; // 新增模式清空原始编码
    }
}, {immediate: true});

// 提交表单
const submitForm = async () => {
    if (!ruleFormRef.value) return;
    await ruleFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const url = ruleForm.id ? 'basic/Account/updateAccount' : 'basic/Account/insertAccount';
                const response = await request.post(url, ruleForm);
                ElMessage.success(ruleForm.id ? '更新客户成功' : '新增客户成功');
                resetForm(); // 提交成功后重置表单
                emit('submit-success'); // 触发事件
            } catch (error) {
                ElMessage.error('操作失败，请稍后重试');
                console.error('操作失败:', error);
            }
        } else {
            ElMessage.warning('请完善表单信息');
        }
    });
};

// 重置表单
const resetForm = () => {
    if (!ruleFormRef.value) return;
    ruleFormRef.value.resetFields();
};

// 取消操作
const emitCancel = () => {
    emit('cancel'); // 通知父组件取消
};
</script>

<style scoped>
.demo-ruleForm {
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 隐藏交易金额输入框的加减按钮 */
.el-input input[type="number"]::-webkit-inner-spin-button,
.el-input input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

.el-input input[type="number"] {
    -moz-appearance: textfield; /* Firefox */
}
</style>
```
